#include "arpa/inet.h"
#include "netinet/in.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "sys/socket.h"
#include "unistd.h"

int make_dgram_server_socket(char *ip, int portnum) {
  int sock_id = socket(PF_INET, SOCK_DGRAM, 0);
  if (sock_id == -1) {
    return -1;
  }

  struct sockaddr_in saddr;
  saddr.sin_port = htons(portnum);
  saddr.sin_family = AF_INET;
  saddr.sin_addr.s_addr = inet_addr(ip);

  if (bind(sock_id, (struct sockaddr *)&saddr, sizeof(saddr)) != 0) {
    return -1;
  }

  return sock_id;
}

int make_dgram_client_socket() { return socket(PF_INET, SOCK_DGRAM, 0); }

int make_internet_address(char *host, int port, struct sockaddr_in *addrp) {
  memset((void *)addrp, 0, sizeof(struct sockaddr_in));
  addrp->sin_addr.s_addr = inet_addr(host);
  addrp->sin_port = htons(port);
  addrp->sin_family = AF_INET;
}

int get_internet_address(char *host, int len, int *port,
                         struct sockaddr_in *addrp) {
  strncpy(host, inet_ntoa(addrp->sin_addr), len);
  *port = ntohs(addrp->sin_port);
  return 0;
}